/*
 * Copyright (c) 2006-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.livejournal;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EventObject;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import org.jdesktop.swingx.JXBusyLabel;
import org.panteleyev.blogclient.BloggerFrame;
import org.panteleyev.blogclient.FontManager;
import org.panteleyev.blogclient.Icon;
import org.panteleyev.blogclient.Options;
import org.panteleyev.livejournal.events.BanListUpdatedEvent;
import org.panteleyev.ljapi.LJAccount;
import org.panteleyev.ljapi.LJException;
import org.panteleyev.swing.SimpleComboBoxModel;
import org.panteleyev.swing.SwingFactory;
import org.panteleyev.swing.events.FontsUpdatedEvent;
import org.panteleyev.utilities.events.AppEventListener;

/**
 *
 * @author  Petr Panteleyev
 */
public class AdminConsoleFrame extends BloggerFrame<LJUserProfile> {
    private JComboBox commandComboBox;
    private JTextArea responseTextArea;

    private Runnable release = new Runnable() {
        @Override
        public void run() {
            busyLabel.setBusy(false);
            executeCommandAction.setEnabled(true);
        }
    };

    private class CommandThread extends Thread {
        private String cmd;

        CommandThread(String cmd) {
            this.cmd = cmd;
        }

        @Override
        public void run() {
            try {
                final ArrayList<String> response = new ArrayList<>();
                account.consoleCommand(cmd, response);

                final StringBuilder text = new StringBuilder();
                for (String s : response) {
                    text.append(s);
                    text.append("\n");
                }

                if (cmd.startsWith("ban_set") || cmd.startsWith("ban_unset")) {
                    getProfile().sendApplicationEvent(new BanListUpdatedEvent(this));
                }

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        if (!response.isEmpty()) {
                            consoleHistory.add(0, cmd);
                            cmdListModel.fireListDataChanged();
                        }
                        responseTextArea.setText(text.toString());
                    }
                });
            } catch (IOException | LJException e) {
                handleException(e);
            } finally {
                SwingUtilities.invokeLater(release);
            }
        }
    }


    private LJAccount account;
    private ArrayList<String> consoleHistory = new ArrayList<>();
    private SimpleComboBoxModel cmdListModel;
    private JXBusyLabel busyLabel = new JXBusyLabel(new Dimension(16, 16));

    /* Actions */
    private AbstractAction executeCommandAction;

    public AdminConsoleFrame(LJUserProfile profile) {
        super(profile);
        this.account = profile.getAccount();

        createActions();
        initComponents();
        createMenuBar();

        cmdListModel = new SimpleComboBoxModel() {
            @Override
            public int getSize() { return consoleHistory.size(); }
            @Override
            public Object getElementAt(int index) { return consoleHistory.get(index); }
        };
        commandComboBox.setModel(cmdListModel);
        commandComboBox.setSelectedItem(null);

        commandComboBox.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {}

            @Override
            public void keyPressed(KeyEvent e) { }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    onSend();
                }
            }
        });

        setIconImage(Icon.CONSOLE.I().getImage());

        addAppEventListener(FontsUpdatedEvent.class, new AppEventListener() {
            @Override
            public void eventReceived(EventObject event) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        updateFont();
                    }
                });
            }
        });

        Options.getBounds(this);
    }

    private void updateFont() {
        if (FontManager.getLJAdminConsoleFont() != null) {
            responseTextArea.setFont(FontManager.getLJAdminConsoleFont());
        }
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        if (b) {
            commandComboBox.requestFocus();
        }
    }

    private void createActions() {
        executeCommandAction = new AbstractAction(L10N.ADMIN_CONSOLE_EXECUTE_ACTION.s()) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                onSend();
            }
        };
    }

    private void createMenuBar() {
        createMenuBar(
            createFileMenu(),
            createProfileMenu(),
            createToolsMenu(),
            createWindowMenu(),
            createHelpMenu()
        );
    }

    private void initComponents() {
        setTitle(L10N.ADMIN_CONSOLE_TITLE.s());
        getContentPane().setLayout(new BorderLayout());

        getContentPane().add(
            SwingFactory.createPanel(BorderFactory.createEmptyBorder(0, 5, 0, 5),
                SwingFactory.LAYOUT.BOX_X,
                createProfileToolBar(false, true),
                Box.createHorizontalGlue(),
                busyLabel
            ), BorderLayout.NORTH
        );

        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(
            SwingFactory.createPanel(BorderFactory.createEmptyBorder(5, 5, 5, 5),
                SwingFactory.LAYOUT.BOX_X,
                new JLabel(L10N.ADMIN_CONSOLE_COMMAND_LABEL.s()),
                Box.createHorizontalStrut(3),
                commandComboBox = new JComboBox(),
                Box.createHorizontalStrut(5),
                new JButton(executeCommandAction)
            ), BorderLayout.NORTH
        );
        topPanel.add(new JScrollPane(responseTextArea = new JTextArea()), BorderLayout.CENTER);

        getContentPane().add(topPanel, BorderLayout.CENTER);

        commandComboBox.setEditable(true);
        updateFont();
    }

    private void onSend() {
        String cmd = (String)commandComboBox.getSelectedItem();
        if (cmd != null && !cmd.isEmpty()) {
            executeCommandAction.setEnabled(false);
            busyLabel.setBusy(true);
            new CommandThread(cmd).start();
        }
    }

}
